package top.heue.text;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.preference.PreferenceManager;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.material.appbar.CollapsingToolbarLayout;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.textfield.TextInputEditText;
import com.google.android.material.textview.MaterialTextView;

import java.util.List;

import top.heue.text.adapter.MainListAdapter;
import top.heue.text.bean.MainListBean;
import top.heue.text.sql.SQLite;
import top.heue.text.util.RunUtil;

public class ScrollingActivity extends AppCompatActivity {
    private RecyclerView main_list;
    private MainListAdapter mainListAdapter;

    //检查表是否存在、检查权限，跳转页面
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_scrolling);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        CollapsingToolbarLayout toolBarLayout = findViewById(R.id.toolbar_layout);
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(ScrollingActivity.this);
        toolBarLayout.setTitle(sharedPreferences.getString("actionbarTitle", "(^-^)/"));
        FloatingActionButton fab = findViewById(R.id.fab);
        fab.setOnClickListener(view -> {
            //跳转到添加相关
            startAddText();
        });
        initView();
    }

    private void startAddText() {
        Dialog dialog = new Dialog(this, R.style.MainDialogStyle);
        @SuppressLint("InflateParams") View contentView = LayoutInflater.from(this).inflate(R.layout.dialog_add, null);
        TextInputEditText title = contentView.findViewById(R.id.dialog_edt_title);
        TextInputEditText content = contentView.findViewById(R.id.dialog_edt_content);
        contentView.findViewById(R.id.dialog_btn_add).setOnClickListener(v -> {
            String titleStr = title.getText().toString();
            String contentStr = content.getText().toString();
            if (titleStr.length() != 0 && contentStr.length() != 0) {
                addToSQLAndList(titleStr, contentStr);
                dialog.dismiss();
            } else {
                Toast.makeText(this, "请勿留空", Toast.LENGTH_SHORT).show();
            }
        });
        dialog.setContentView(contentView);
        dialog.setTitle("添加内容");
        dialog.show();
    }

    private void addToSQLAndList(String title, String content) {
        SQLite sqLite = new SQLite(this);
        String id = String.valueOf(sqLite.insert(title, content));
        content = RunUtil.contentFormat(this, content);
        MainListBean mainListBean = new MainListBean(id, title, content);
        mainListAdapter.addItem(mainListBean);
        main_list.getLayoutManager().scrollToPosition(0);
    }

    private void initView() {
        SQLite sqLite;
        //SQLite sqLite = new SQLite(this);
        //sqLite.createTable();
        main_list = findViewById(R.id.main_list);
        List<MainListBean> list;
        //MainListBean mainListBean;
        if (RunUtil.isFirstRun(this)) {
            sqLite = new SQLite(this);
            sqLite.createTable();
            sqLite = new SQLite(this);//添加问候文章
            sqLite.insert("你好", "  很高兴见到你。" +
                    "\n  这是一个方便读拼音的应用。对于多音字虽然音可能不对，但知道平舌翘舌音足矣..." +
                    "\n  如果你有什么好的建议，欢迎留言。" +
                    "\n  如果对本应用感到满意，也欢迎五星好评~");
        }

        sqLite = new SQLite(this);
        list = sqLite.listAll();
        Log.i("Mine", String.valueOf(list.size()));
        main_list.setLayoutManager(new LinearLayoutManager(ScrollingActivity.this));
        main_list.setItemAnimator(new DefaultItemAnimator());
        mainListAdapter = new MainListAdapter(list);
        main_list.setAdapter(mainListAdapter);
        mainListAdapter.setOnItemClickListener((view, position) -> {
                    Intent intent = new Intent(ScrollingActivity.this, ContentActivity.class);
                    String id = mainListAdapter.getItem(position).id;
                    intent.putExtra(ContentActivity.ContentId, id);
                    startActivity(intent);
                });
        mainListAdapter.setOnItemLongClickListener((view, position) -> startDeleteText(position));

    }

    private void startDeleteText(int position) {
        Dialog dialog = new Dialog(this);
        @SuppressLint("InflateParams") View contentView = LayoutInflater.from(this).inflate(R.layout.dialog_delete, null);
        MainListBean mainListBean = mainListAdapter.getItem(position);
        String tips = "确定删除：\"" + mainListBean.title + "\"?\n这是不可逆的";
        MaterialTextView materialTextView = contentView.findViewById(R.id.dialog_del_txt_tips);
        materialTextView.setText(tips);
        contentView.findViewById(R.id.dialog_del_btn_sure).setOnClickListener(v -> {
            deleteText(mainListBean);
            dialog.dismiss();
        });
        contentView.findViewById(R.id.dialog_del_btn_cancel).setOnClickListener(v -> dialog.dismiss());
        dialog.setContentView(contentView);
        Window window = dialog.getWindow();
        window.setGravity(Gravity.BOTTOM);
        window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        dialog.show();
    }

    private void deleteText(MainListBean mainListBean) {
        SQLite sqLite = new SQLite(this);
        sqLite.delete(mainListBean.id);
        mainListAdapter.deleteItem(mainListBean);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_scrolling, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            //跳转到设置界面
            Intent intent = new Intent(ScrollingActivity.this, SettingsActivity.class);
            startActivity(intent);
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}